import express from 'express'
import {checkLogin,checkUserRole} from './middleWare/index.js'
import {dateRegex} from '../utils/index.js'

import  tableModule from '../models/index.js';
const {
    recentPlansModel,
    taskListModel,
    thingsModelListModel,
    thingBranchModelListModel,
    listOfItemsModel,
} = tableModule



const router = express.Router()
router.use(checkLogin)
router.use(checkUserRole)




// 新增近期计划
/**
 * deadline: yyyy-mm-dd
 */
router.post("/addRecentPlan", async (req,res)=>{
    const {userId} = req
    const {roleCode,plans} = req.body

    if(roleCode && plans?.length>0 && userId){
       let fullSuccess = await recentPlansModel.addBatchRecentPlan({
            userInfo: {userId, roleCode},   
            recentPlanDataList: plans
        })

        if(fullSuccess){
            return  res.json({
                code:200,
                message:"新增成功",
                data:true
            })
        }else{
            return res.status(500).json({
                code:500,
                message:"部分参数不完整或格式错误，未添加成功",
                data:null
            })
        }
    }else{
        return res.status(500).json({
            code:500,
            message:"传参不完整",
            data:null
        })
    }
})


// 查询登录用户的近期计划
router.post("/searchRecentPlan", async (req,res)=>{
    const {userId} = req
    const {roleCode} = req.body

    if(userId && roleCode){
        let searchRes = await recentPlansModel.getRecentPlansByUserIdAndRoleCode({
            userId,
            roleCode
        })
        let result = searchRes.map(item => ({
            "id": item.id,
            // "roleCode": item.roleCode,
            "planName": item.planName,
            "deadline": item.deadline,
        })) 

        return res.json({
            code:200,
            message:"查询成功",
            data:result,
            total:result.length
        })
    }else{
        return res.status(500).json({
            code:500,
            message:"参数信息不完整",
            data:null
        })
    }
})


// 新增今日任务(目前只能增当天的)
router.post("/addTodayTask", async (req,res)=>{
    const {userId} = req
    const {roleCode,task} =  req.body
    const {taskName, startTime,endTime,isAlarmClock, isUrgency} = task;

    let timeRegex = /[0-5][0-9]:[0-5][0-9]/
    
    if( userId && 
        roleCode && 
        task  &&
        taskName && 
        startTime && 
        timeRegex.test(startTime) &&
        endTime && 
        timeRegex.test(endTime) &&
        (typeof isAlarmClock === 'boolean') && 
        (typeof isUrgency === 'boolean')
    ){
        let addRes = await taskListModel.addTask({
            userInfo: {userId, roleCode},
            taskData: task
        })

        if(addRes){
            return res.json({
                code:200,
                message:"新增成功",
                data:true
            })
        }else{
            return res.status(500).json({
                code:500,
                message:"新增失败",
                data:null
            })
        }
    }else{
        return res.status(500).json({
            code:500,
            message:"传参不完整或格式错误",
            data:null
        })
    }
})


// 查询今日任务
router.post("/searchTodayTask", async (req,res)=>{
    const {userId} = req
    const {roleCode,date,isUrgency} = req.body

    if(userId && roleCode && date && (typeof isUrgency === 'boolean') && dateRegex.test(date)){
        let result = await taskListModel.getTodayTask({userId,roleCode,date,isUrgency})
        res.json({
            code:200,
            "message":"查询成功",
            "data":result,
            "total":result.length
        })
    }else{
        res.status(500).json({
            code:500,
            message:"传参缺失或格式错误",
            data:null
        })
    }
})



// 新增事项清单模块列表
router.post("/addThingsModel",async (req,res)=>{
    const {userId} = req
    const {roleCode,thingsModel} = req.body
    const {modelName, theme} = thingsModel || {}

    if(userId && roleCode && thingsModel && modelName && theme){
        let addRes = await thingsModelListModel.addThingsModelList({
            userInfo: {userId, roleCode},
            thingsModelData: thingsModel 
        })
        if(addRes){
            return res.json({
                code:200,
                message:"添加成功",
                data:true
            })
        }else{
            return res.status(500).json({
                code:500,
                message:"新增失败",
                data:null
            })
        }
    }else{
        return res.status(500).json({
            code:500,
            message:"传参参不完整",
            data:null
        })
    }
})



// 查询事项清单模块列表
router.post("/searchThingsModelList",async (req,res)=>{
    const {userId} = req
    const {roleCode} = req.body

    if(userId && roleCode){
        let searchRes = await thingsModelListModel.getThingsModelListByUserIdAndRoleCode({
            userId,
            roleCode
        })
        let result = searchRes.map(item => ({
            id:item.id,
            modelName:item.modelName,
            theme:item.theme,
            createTime:item.createTime  
        }))

        return res.json({
            code:200,
            message:"查询成功",
            data:result,
            total:result.length
        })
    }else{
        return res.status(500).json({
            code:500,
            message:"传参不完整",
            data:null
        })
    }    
})



//新增事项清单模块分支模块(分两类)
router.post("/addThingModeDetailList",async (req,res)=>{
    const {userId} = req
    const {roleCode,thingModelId,detailContent,thingModelBranchId } = req.body
    const {subTitle,status,content} = detailContent
   
    if(userId && 
        roleCode && 
        thingModelId && 
        // 事项id存在
        await thingsModelListModel.getThingModelById(thingModelId) &&
        detailContent
    ){
        if(thingModelBranchId){
            // 添加清单模块子内容下的子内容
            let branchModel = await thingBranchModelListModel.getBranchModelById(thingModelBranchId)
            if(branchModel && subTitle){
                    let addRes = await listOfItemsModel.addListOfItems({
                        userId,roleCode,thingModelId,
                        thingModelBranchId,listName:subTitle,
                        status:status ? status : 0 , 
                        content })

                    if(!addRes){
                        return res.status(500).json({
                            code:500,
                            message:"新增失败",
                            data:null
                        })
                    }
            }else{
                return res.status(500).json({
                    code:500,
                    message:"父级信息不存在或者参数缺失,新增失败",
                    data:null
                })
            }


        }else{
            // 添加清单模块子内容信息
            if(subTitle){
                let addRes = await thingBranchModelListModel.addThingBranchModel({userId,roleCode,thingModelId,title:subTitle})
                if(!addRes){
                    return res.status(500).json({
                        code:500,
                        message:"新增失败",
                        data:null
                    })
                }
            }else{
                return res.status(500).json({
                    code:500,
                    message:"参数传参不完整，新增失败",
                    data:null
                })
            }
        }

        return res.json({
            code:200,
            message:"新增成功",
            data:true
        })

    }else{
        return res.status(500).json({
            code:500,
            message:"传参不完整或传参错误",
            data:null
        })
    }
})


// 查询事项清单具体内容
router.post("/searchThingModeDetailList",async (req,res)=>{
    const {userId} = req
    const {roleCode,thingModelId} = req.body
    if(userId && roleCode && thingModelId){
        let branchModelsRes = await thingBranchModelListModel.getBranchModelsByThingModelId(thingModelId)
        let result = await branchModelsRes.map( async(item)=>{
            let listOfItemRes = await listOfItemsModel.getListOfItemsByThingModelBranchId(item.id)
            listOfItemRes = listOfItemRes.map((subItem)=>{
                return {
                    id:subItem.id,
                    itemTitle:subItem.itemName,
                    status:subItem.status,
                    content:subItem.content,
                }
            })
            return {
                id:item.id,
                subTitle:item.listName,
                sublist:listOfItemRes,
                listTotal:listOfItemRes.length

            }
        })
        Promise.all(result).then((resolvedResult) => {
            return  res.json({
                code:200,
                message:"查询成功",
                data:resolvedResult,
                listTotal:resolvedResult.length
            })
        }).catch((error) => {
            return res.status(500).json({
                code:500,
                message:"查询失败",
                data:null
            })  
        });
    }else{
        return res.status(500).json({
            code:500,
            message:"传参不完整",
            data:null
        })
    }
})



export default router